﻿using DAL;
using Entity.Models.dto;
using Entity.Models.Entities;
using Entity.Models.vo;
using IBLL;
using IDAL;
using RepositorySys.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using utils;
using utils.enums;
using utils.Enums;
using utils.EX;
using Utils;
using Utils.enums;

namespace BLL
{
    /// <summary>
    /// 角色管理业务层
    /// </summary>
    public class RoleInfoBLL: IRoleInfoBLL
    {
        //角色dal
        IRoleInfoDAL roleInfoDAL;
        
        //用户dal
        IUserDAL _userDAL;

        //用户bll
        IUserBLL _userBLL;

        //绑定角色dal
        IR_UserInfo_RoleInfoDAL _UserInfo_RoleInfoDAL;

        //绑定菜单dal
        IR_RoleInfo_MenuInfoDAL _r_RoleInfo_MenuInfoDAL;

        public RoleInfoBLL(IRoleInfoDAL roleInfoDAL, IR_UserInfo_RoleInfoDAL UserInfo_RoleInfoDAL, IUserDAL userDAL, IUserBLL userBLL, IR_RoleInfo_MenuInfoDAL r_RoleInfo_MenuInfoDAL)
        {
            this.roleInfoDAL = roleInfoDAL;
            this._UserInfo_RoleInfoDAL = UserInfo_RoleInfoDAL;
            this._userDAL = userDAL;
            this._userBLL = userBLL;
            this._r_RoleInfo_MenuInfoDAL = r_RoleInfo_MenuInfoDAL;
        }

        /// <summary>
        /// 角色列表、搜索
        /// </summary>
        /// <returns></returns>
        public List<RoleInfoDTO> getRoleShow(string roleInfoName,string page,string limit,out int cont)
        {
            IQueryable<RoleInfo> search = roleInfoDAL.getEntitys().Where(d => d.IsDelete != true);
            if (!string.IsNullOrEmpty(roleInfoName))
            {
                search = search.Where(d => d.IsDelete != true && d.RoleName.Contains(roleInfoName));
            }
            
            //分页
            var page_list = search.OrderByDescending(md => md.CreateTime).Skip((int.Parse(page) - 1) * int.Parse(limit)).Take(int.Parse(limit)).ToList();
            cont = search.Count();

            List<RoleInfoDTO> RoleInfo = new List<RoleInfoDTO>();
            foreach (var item in page_list)
            {
                RoleInfo.Add(new RoleInfoDTO(item));
            }
            return RoleInfo;
        }

        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// <param name="roleInfoInfo"></param>
        /// <returns></returns>
        public bool AddRoleInfo(RoleInfo roleInfoInfo)
        {
            roleInfoInfo.Id = Guid.NewGuid().ToString();
            roleInfoInfo.CreateTime = DateTime.Now;
            //根据账号查询角色信息
            RoleInfo byroleInfoInfo = roleInfoDAL.getEntitys().FirstOrDefault(d => d.IsDelete != true && d.RoleName == roleInfoInfo.RoleName);
            if (byroleInfoInfo == null)
            {
                //保存
                if (roleInfoDAL.AddEntity(roleInfoInfo) < 0)
                {
                    throw new MyException(((int)UserEnums.USER_STATE.LOSE), Enums.getDescribe(UserEnums.USER_STATE.LOSE));
                }
            }
            else
            {
                throw new MyException(((int)DepartmentEnums.STATE.ALREADY),"角色已存在");
            }
            return true;
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="roleInfoIds"></param>
        /// <returns></returns>
        public bool DatateRoleInfos(List<string> roleInfoIds)
        {
            if (roleInfoIds.Count > 0)
            {
                foreach (var item in roleInfoIds)
                {
                    DatateRoleInfo(item);
                }
            }
            else
            {
                throw new MyException(((int)UserEnums.USER_STATE.UPDATE_LIST), Enums.getDescribe(UserEnums.USER_STATE.UPDATE_LIST));
            }
            return true;
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="roleInfoId"></param>
        /// <returns></returns>
        public bool DatateRoleInfo(string roleInfoId)
        {
            if (roleInfoDAL.SoftDalateEntity(roleInfoId) < 0)
            {
                throw new MyException(((int)UserEnums.USER_STATE.DATATE_LOSE), Enums.getDescribe(UserEnums.USER_STATE.DATATE_LOSE));
            }
            return true;
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="roleInfo"></param>
        /// <returns></returns>
        public bool UpdateRoleInfo(RoleInfo roleInfo)
        {
            var Role = roleInfoDAL.getByEntityId(roleInfo.Id);
            Role.RoleName = roleInfo.RoleName;
            Role.Description = roleInfo.Description;
            //判断是否成功
            if (roleInfoDAL.UpdataEntity(Role) < 0)
            {
                throw new MyException(((int)UserEnums.USER_STATE.UPDATE_LOSE), Enums.getDescribe(UserEnums.USER_STATE.UPDATE_LOSE));
            }
            return true;
        }

        /// <summary>
        /// 根据id查询角色信息
        /// </summary>
        /// <param name="roleInfoid"></param>
        /// <returns></returns>
        public RoleInfo getbyRoleInfoId(string roleInfoid)
        {
            return roleInfoDAL.getEntitys().Where(u => u.IsDelete != true).FirstOrDefault(u => u.Id.EndsWith(roleInfoid));
        }

        /// <summary>
        /// 获取角色下已选角色
        /// </summary>
        /// <param name="roleId"></param>
        public List<string> getSelectedUser(string roleId)
        {
            return _UserInfo_RoleInfoDAL.getEntitys().Where(u => u.RoleId.EndsWith(roleId)).Select(u => u.UserId).ToList();
        }

        /// <summary>
        /// 绑定角色
        /// </summary>
        /// <param name="userId">角色id</param>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        public bool BinUser_Role(List<string> userId, string roleId)
        {
            //获取角色下角色id
            List<string> role_userIds = _UserInfo_RoleInfoDAL.getEntitys().Where(u => u.RoleId.EndsWith(roleId)).Select(u => u.UserId).ToList();
           
            //解绑
            UnpinlessRole(userId, role_userIds);

            //绑定
            BindingRole(userId, roleId, role_userIds);

            return true;
        }

        /// <summary>
        /// 绑定角色
        /// </summary>
        /// <param name="userId">角色id</param>
        /// <param name="roleId">角色id</param>
        /// <param name="role_userIds">角色下角色id</param>
        private void BindingRole(List<string> userId, string roleId, List<string> role_userIds)
        {
            foreach (var item in userId)
            {
                if (!role_userIds.Any(u => u.EndsWith(item)))
                {
                    R_UserInfo_RoleInfo r_UserInfo_RoleInfo = new R_UserInfo_RoleInfo(item, roleId);
                    r_UserInfo_RoleInfo.Id = Guid.NewGuid().ToString();
                    _UserInfo_RoleInfoDAL.AddEntity(r_UserInfo_RoleInfo);
                }
            }
        }

        /// <summary>
        /// 解绑角色
        /// </summary>
        /// <param name="userId">角色id</param>
        /// <param name="role_userIds">角色下角色id</param>
        private void UnpinlessRole(List<string> userId, List<string> role_userIds)
        {
            foreach (var item in role_userIds)
            {
                if (!userId.Any(u => u.EndsWith(item)))
                {
                    _UserInfo_RoleInfoDAL.DalateEntity(item);
                }
            }
        }

        /// <summary>
        /// 绑定菜单
        /// </summary>
        /// <param name="menuId"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public bool BinMenu_Role(List<string> menuId, string roleId)
        {
            //根据角色id查询菜单id
            List<string> role_menuIds = _r_RoleInfo_MenuInfoDAL.getEntitys().Where(u => u.RoleId.EndsWith(roleId)).Select(u => u.MenuId).ToList();

            //解绑
            foreach (var item in role_menuIds)
            {
                if (!menuId.Any(u => u.EndsWith(item)))
                {
                    _r_RoleInfo_MenuInfoDAL.DalateEntity(item);
                }
            }

            //绑定菜单
            foreach (var item in menuId)
            {
                if (!role_menuIds.Any(u => u.EndsWith(item)))
                {
                    _r_RoleInfo_MenuInfoDAL.AddEntity(new R_RoleInfo_MenuInfo(item, roleId));
                }
            }

            return true;
        }


        /// <summary>
        /// 获取已选菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<string> getSelectedMenu(string roleId)
        {
            return _r_RoleInfo_MenuInfoDAL.getEntitys().Where(u => u.RoleId.EndsWith(roleId)).Select(u => u.MenuId).ToList();
        }
    }
}
